<?php

namespace common\components;

/**
 * @author  shuang
 * @date    2016-10-31 13:27:43
 * @version V1.0
 * @desc    
 */
use yii\base\Event;
use frontend\models\WB_Task;
use frontend\models\WB_UserAccount;
use yii\helpers\ArrayHelper;
use frontend\models\WB_TaskReflesh;
use frontend\models\WB_UserPayRecord;
use Yii;
use common\components\MTools;
use frontend\models\WB_TaskTop;
use frontend\models\WB_UserProfile;

class TaskEvent extends Event {
    /*
     * 检测任务是否存在
     * @return model
     */

    protected function taskExist() {
        $model = WB_Task::findOne(ArrayHelper::getValue($this->data, "hidid"));
        if (!$model instanceof WB_Task) {
            throw new \yii\web\NotFoundHttpException();
        }
        /*
         * 检测用户终止项目，退款是否完成
         */
        if ($model->status == 68 && (time() - $model->stopdate) < 600) {
            $this->sender->message = "对不起，当前任务已被终止【" . Yii::$app->formatter->asDatetime($model->stopdate + 600) . "】退款完成之后，才能操作！";
        }
        return $model;
    }

    /*
     * 数据模型错误提示
     * @params $array ["errors"=>[]]
     */

    private function errorMessage($errors) {
        foreach ($errors as $item) {
            $this->sender->message = $item[0];
            break;
        }
    }

    /*
     * 任务数量判定
     */

    protected function checkTasksingleCount() {
        if (ArrayHelper::getValue($this->data, "number") < MTools::getYiiParams("single_task_votes")) {
            $this->sender->message = "单次任务" . MTools::getYiiParams("single_task_votes") . "票起";
        }
    }

    /*
     * 添加交易、更新账户
     */

    protected function createTradeRecord() {
        $type = ArrayHelper::getValue($this->data, "type");
        $class_type = ArrayHelper::getValue($this->data, "class_type");
        $note = ArrayHelper::getValue($this->data, "note");
        if ($type === 2) {
            $taskmoney = -ArrayHelper::getValue($this->data, "taskmoney");
        } else {
            $taskmoney = ArrayHelper::getValue($this->data, "taskmoney");
        }
        if ($type && $class_type) {
            return WB_UserPayRecord::createRecord(ArrayHelper::getValue($this->data, "userid"), $taskmoney, $type, $class_type, $note ? $note : null);
        } else {
            $this->sender->message = "交易类型异常";
        }
        return false;
    }

    /*
     * 添加返利充值
     */

    protected function createRebateTradeRecord() {
        $invite_code = ArrayHelper::getValue($this->data, "invite_code");
        if ($invite_code !== MTools::getYiiParams("sys_invite_code")) {
            //返利
        }
        return true;
    }

    /*
     * 统计已经完成
     * @params $taskid
     */

    protected function countCompleteTask($taskid) {
        return \frontend\models\WB_UserTaskOperate::find()->where("status=1 and taskid=" . $taskid)->count();
    }

    /*
     * 任务是非执行中
     * @params $status
     */

    protected function taskNoruning($status) {
        if ($status !== 67) {
            $this->sender->message = "任务不在执行中";
        }
    }

    /*
     * 账户金额判断
     */

    protected function checkAccount($note = null) {
        if (ArrayHelper::getValue($this->data, "isdedu") !== true) {
            $useraccount = WB_UserAccount::find()->where("userid=" . ArrayHelper::getValue($this->data, "userid"))->one();
            if (!$useraccount instanceof WB_UserAccount) {
                throw new \yii\web\NotFoundHttpException();
            }
            if ($useraccount->amount < ArrayHelper::getValue($this->data, "taskmoney")) {
                $this->sender->message = $note ? $note . "账户余额：" . $useraccount->amount . "！" : "对不起，账户金额不够请及时充值任务金额：" . ArrayHelper::getValue($this->data, "taskmoney") . "元，账户余额：" . $useraccount->amount . "！";
            }
        }
    }

    /*
     * 检测任务是否打包过
     */

    protected function compDabao($taskid) {
        $model = \frontend\models\WB_TaskDabao::find()->where("taskid=$taskid")->one();
        if ($model instanceof \frontend\models\WB_TaskDabao) {
            $model->ispack = 0;
            return $model->update();
        }
        return true;
    }

    /*
     * 添加刷新任务
     */

    protected function addTaskreflesh() {
        $reno = ArrayHelper::getValue($this->data, "reno");
        if ($reno <= 0) {
            $this->sender->message = "刷新任务次数必须大于0";
            return false;
        }
        $result = WB_TaskReflesh::createTaskreflesh(ArrayHelper::getValue($this->data, "hidid"), $reno, ArrayHelper::getValue($this->data, "auto"));
        if ($result !== true) {
            $this->errorMessage(ArrayHelper::getValue($result, "errors"));
            return false;
        }
        return true;
    }

    /*
     * 添加任务
     */

    protected function addTask() {
        $result = WB_Task::createData();
        if ($result !== true) {
            $this->errorMessage(ArrayHelper::getValue($result, "errors"));
            return false;
        }
    }

    /*
     * 添加置顶
     */

    protected function addTasktop() {
        $result = WB_TaskTop::createTasktop(ArrayHelper::getValue($this->data, "hidid"));
        if ($result !== true) {
            $this->errorMessage(ArrayHelper::getValue($result, "errors"));
            return false;
        }
    }

    /*
     * 发布任务
     */

    public function issueTask() {
        $this->checkTasksingleCount();
        if (!empty($this->sender->message)) {
            return false;
        }
        $this->checkAccount();
        if (!empty($this->sender->message)) {
            return false;
        }
        $trans = Yii::$app->db->beginTransaction();
        try {
            if ($this->addTask() !== false) {
                if ($this->createTradeRecord() === true) {
                    $trans->commit();
                    $this->sender->flag = true;
                    $this->sender->message = ArrayHelper::getValue($this->data, "operateMsg") . "：操作成功";
                }
            }
        } catch (Exception $ex) {
            $trans->rollBack();
            throw new \yii\web\NotFoundHttpException($ex);
        }
    }

    /*
     * 刷新任务
     */

    public function reflashTask() {
        $taskmodel = $this->taskExist();
        if (!empty($this->sender->message)) {
            return false;
        }
        $this->taskNoruning($taskmodel->status);
        if (!empty($this->sender->message)) {
            return false;
        }
        $this->checkAccount();
        if (!empty($this->sender->message)) {
            return false;
        }
        $trans = Yii::$app->db->beginTransaction();
        try {
            if ($this->addTaskreflesh() && (ArrayHelper::getValue($this->data, "isdedu") === true || $this->createTradeRecord())) {
                $trans->commit();
                $this->sender->flag = true;
                $this->sender->message = ArrayHelper::getValue($this->data, "operateMsg") . "：操作成功";
            }
        } catch (Exception $ex) {
            $trans->rollBack();
            throw new \yii\web\NotFoundHttpException($ex);
        }
    }

    /*
     * 追加任务数量
     */

    public function addTaskNumber() {
        if (ArrayHelper::getValue($this->data, "number") > 0) {
            $taskmodel = $this->taskExist();
            if (!empty($this->sender->message)) {
                return false;
            }
            $this->checkAccount();
            if (!empty($this->sender->message)) {
                return false;
            }
            $trans = Yii::$app->db->beginTransaction();
            try {
                $taskmodel->end_at = Yii::$app->request->post("end_at") ? strtotime(Yii::$app->request->post("end_at")) : null;
                $taskmodel->number = $taskmodel->number + ArrayHelper::getValue($this->data, "number");
                $taskmodel->status = 67;
                $taskmodel->stopdate = null;
                if ($taskmodel->update()) {
                    if (ArrayHelper::getValue($this->data, "isdedu") === true || $this->createTradeRecord() === true) {
                        $trans->commit();
                        $this->sender->flag = true;
                        $this->sender->message = ArrayHelper::getValue($this->data, "operateMsg") . "：操作成功";
                    }
                } else {
                    $this->sender->message = "追加任务数量失败";
                }
            } catch (Exception $ex) {
                $trans->rollBack();
                throw new \yii\web\NotFoundHttpException($ex);
            }
        } else {
            $this->sender->message = "追加任务数量必须大于0";
        }
    }

    /*
     * 添加置顶任务
     */

    public function addTaskTopEvent() {
        $taskmodel = $this->taskExist();
        if (!empty($this->sender->message)) {
            return false;
        }
        $this->taskNoruning($taskmodel->status);
        if (!empty($this->sender->message)) {
            return false;
        }
        $this->checkAccount();
        if (!empty($this->sender->message)) {
            return false;
        }
        $trans = Yii::$app->db->beginTransaction();
        try {
            if ($this->addTasktop() !== false) {
                if (ArrayHelper::getValue($this->data, "isdedu") === true || $this->createTradeRecord() === true) {
                    $trans->commit();
                    $this->sender->flag = true;
                    $this->sender->message = ArrayHelper::getValue($this->data, "operateMsg") . "：操作成功";
                }
            }
        } catch (Exception $ex) {
            $trans->rollBack();
            throw new \yii\web\NotFoundHttpException($ex);
        }
    }

    /*
     * 注册事件
     */

    public function addRegisterEvent() {
        $model = ArrayHelper::getValue($this->data, "model");
        //验证表单数据
        if (!$model->validate()) {
            $this->errorMessage($model->errors);
            return false;
        }
        $trans = Yii::$app->db->beginTransaction();
        try {
            $user = new \common\models\User();
            $user->username = $model->username;
            $user->role = 1;
            $user->my_code = MTools::makeOnlyNumber();
            $user->setPassword($model->password);
            $user->generateAuthKey();
            $user->generatePasswordResetToken();
            if ($user->save()) {
                //保存基本信息
                $res = WB_UserProfile::find()->where("userid=" . $user->id)->one();
                $userprofile = $res instanceof WB_UserProfile ? $res : new WB_UserProfile();
                $userprofile->userid = $user->id;
                $userprofile->username = $model->username;
                $userprofile->invite_code = $model->invite_code;
                $userprofile->truename = $model->truename;
                $userprofile->alipay = $model->alipay;
                $userprofile->qq = $model->qq;
                $userprofile->gradeid = 1;
                $userprofile->phone = $model->phone;
                $this->data["userid"] = $user->id;
                $this->data["invite_code"] = $model->invite_code;
                if ($userprofile->save() && WB_UserAccount::addAccount($user->id) && $this->createRebateTradeRecord() && Yii::$app->getUser()->login($user)) {
                    $trans->commit();
                    $this->sender->flag = 1;
                    $this->sender->message = "注册成功";
                } else {
                    $this->sender->message = "注册失败";
                }
            } else {
                $this->sender->message = "注册失败";
            }
        } catch (Exception $ex) {
            $trans->rollBack();
            throw new \yii\web\NotFoundHttpException($ex);
        }
    }

    /*
     * 编辑任务
     */

    public function editTask() {
        $this->taskExist();
        if (!empty($this->sender->message)) {
            return false;
        }
        $trans = Yii::$app->db->beginTransaction();
        try {
            $res = WB_Task::editTask(ArrayHelper::getValue($this->data, "hidid"));
            if ($res === true) {
                $trans->commit();
                $this->sender->flag = true;
                $this->sender->message = ArrayHelper::getValue($this->data, "operateMsg") . "：操作成功";
            } else {
                $this->errorMessage(ArrayHelper::getValue($res, "errors"));
                return false;
            }
        } catch (Exception $ex) {
            $trans->rollBack();
            throw new \yii\web\NotFoundHttpException($ex);
        }
    }

    public function editTask2() {
        $this->taskExist();
        if (!empty($this->sender->message)) {
            return false;
        }
        $trans = Yii::$app->db->beginTransaction();
        try {
            $res = WB_Task::editTask2(ArrayHelper::getValue($this->data, "hidid"));
            if ($res === true) {
                $trans->commit();
                $this->sender->flag = true;
                $this->sender->message = ArrayHelper::getValue($this->data, "operateMsg") . "：操作成功";
            } else {
                $this->errorMessage(ArrayHelper::getValue($res, "errors"));
                return false;
            }
        } catch (Exception $ex) {
            $trans->rollBack();
            throw new \yii\web\NotFoundHttpException($ex);
        }
    }

    public function checkUpdate() {
        $this->checkAccount("亲对不起！编辑任务描述时，账户余额应不小于100元！");
        if (empty($this->sender->message)) {
            $this->sender->flag = true;
        }
    }

    /*
     * 停止任务
     */

    public function stopTask() {

        $taskmodel = $this->taskExist();

        if (!empty($this->sender->message)) {
            return false;
        }
        $trans = Yii::$app->db->beginTransaction();
        try {
            if ($taskmodel->status == 68) {
                $this->sender->message = "对不起，当前任务已被终止，请不要重复操作!";
                return false;
            }
            //查看任务已经完成情况
            $comcount = $this->countCompleteTask($taskmodel->id);
            if ($taskmodel->number - $comcount > 0) {
                $taskmodel->status = 68;
                $taskmodel->nosheetcount = $taskmodel->number;
                $taskmodel->number = $comcount;
                $taskmodel->stopdate = time();
                $taskmodel->stopcashback = 0;
                //$this->data["taskmoney"] = ($taskmodel->number - $comcount) * MTools::getTaskPrice($taskmodel->task_price_id);
                if ($taskmodel->update() && $this->compDabao($taskmodel->id)) {
                    //检测是否置顶
                    WB_TaskTop::deleteAll("taskid=" . $taskmodel->id);
                    $trans->commit();
                    $this->sender->flag = true;
                    $this->sender->message = ArrayHelper::getValue($this->data, "successnote") ? ArrayHelper::getValue($this->data, "successnote") : ArrayHelper::getValue($this->data, "operateMsg") . "任务终止成功，系统将在【" . Yii::$app->formatter->asDatetime($taskmodel->stopdate + 600) . "】对未完成票数的退款！";
                } else {
                    return false;
                }
            } else {
                $this->sender->message = "任务已经全部接受，完成。返回金额0";
            }
        } catch (Exception $ex) {
            $trans->rollBack();
            throw new \yii\web\NotFoundHttpException($ex);
        }
    }

    /*
     * 打包任务图片
     */

    public function dabaoTask() {
        $taskid = ArrayHelper::getValue($this->data, "hidid");
        $pfop = MTools::Qinudown($taskid);
        $trans = Yii::$app->db->beginTransaction();
        try {
            $model = new \frontend\models\WB_TaskDabao();
            $model->taskid = $taskid;
            $model->ispack = 1;
            $model->pfop = $pfop;
            if ($model->insert()) {
                $trans->commit();
                $this->sender->flag = true;
                $this->sender->message = ArrayHelper::getValue($this->data, "operateMsg") . "：添加压缩任务成功，当刷新页面打包变为打包下载可下载！";
            } else {
                $this->sender->message = "操作失败";
            }
        } catch (Exception $ex) {
            $trans->rollBack();
            throw new \yii\web\NotFoundHttpException($ex);
        }
    }

    /*
     * 定时终止任务的返现
     */

    public function timingCashback() {
        $query = WB_Task::find()->where("userid=" . Yii::$app->user->id);
        $query->andWhere("stopdate < " . (time() - 600) . " and stopcashback = 0");
        $result = $query->all();
        $trans = Yii::$app->db->beginTransaction();
        try {
            if ($result) {
                foreach ($result as $item) {
                    $item->number = $this->countCompleteTask($item->id);
                    $item->stopcashback = 1;
                    $item->update();
                    $this->data["taskmoney"] = ($item->nosheetcount - $item->number) * MTools::getTaskPrice($item->task_price_id);
                    $this->createTradeRecord();
                    $this->compDabao($item->id);
                }
                $trans->commit();
            }
        } catch (Exception $ex) {
            $trans->rollBack();
            throw new \yii\web\NotFoundHttpException($ex);
        }
    }

    /*
     * 系统强制定时终止任务的返现
     */

    public function QtimingCashback() {
        $query = WB_Task::findOne($this->data["taskid"]);
        if ($query && $query->stopcashback == 0) {
            $trans = Yii::$app->db->beginTransaction();
            try {
                if ($query->status == 68) {
                    $query->number = $this->countCompleteTask($query->id);
                    $query->stopcashback = 1;
                    $query->update();
                    $this->data["userid"] = $query->userid;
                    $this->data["taskmoney"] = ($query->nosheetcount - $query->number) * MTools::getTaskPrice($query->task_price_id);
                    if ($this->createTradeRecord() && $this->compDabao($query->id)) {
                        ;
                        $trans->commit();
                        $this->sender->flag = true;
                        $this->sender->message = "操作成功";
                    } else {
                        $this->sender->message = "操作失败";
                    }
                } else {
                    $this->sender->message = "当前任务，并没有终止，不能返现!";
                }
            } catch (Exception $ex) {
                $trans->rollBack();
                throw new \yii\web\NotFoundHttpException($ex);
            }
        } else {
            $this->sender->message = "当前任务不存在或是已将剩余任务返现，不要重复操作";
        }
    }

}
